package com.sliverhark.service.impl;

import com.sliverhark.domain.LoginUser;
import com.sliverhark.domain.ResponseResult;
import com.sliverhark.domain.User;
import com.sliverhark.service.LoginService;
import com.sliverhark.utils.JwtUtil;
import com.sliverhark.utils.RedisCache;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 用户登录方法
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult  login(User user) {
        // AuthenticationManager  authentic进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没通过, 给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败,用户名或密码错误!");
        }

        // 如果认证通过了, 使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入redis userid作key   token:  jwt
        redisCache.setCacheObject("login:" + userId, loginUser);

        return new ResponseResult(200, "登录成功", map);

    }

    /**
     * 用户登出方法
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        // 这边loginUser不一定能获取到, 因为token可能过期
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
       /* if(StringUtils.isBlank(userId.toString())){
            throw new RuntimeException("退出异常,回到退出界面");
        }*/
        // 删除redis中的值
        boolean flag = redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200, "注销成功");
    }
}
